package com.woniuxy.course.service.impl;

import com.aliyun.oss.*;
import com.woniuxy.course.entity.ArticleRelease;
import com.woniuxy.course.mapper.ArticleReleaseMapper;
import com.woniuxy.course.service.ArticleReleaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
import org.springframework.web.multipart.*;


import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cyh
 * @since 2020-07-23
 */
@Service
public class ArticleReleaseServiceImpl extends ServiceImpl<ArticleReleaseMapper, ArticleRelease> implements ArticleReleaseService {

    @Autowired
    private ArticleReleaseMapper articleReleaseMapper;

    //网络上传文件
    @Override
    @Transactional
    public String upload(MultipartFile file) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        String accessKeyId = "LTAI4G4ZNMdvr9ZBBesGncKK";
        String accessKeySecret = "vKTiLbiRojXKZFKYszWNRSZTx7e3us";
        String bucketName = "course-0723";
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        filename = uuid + filename;
        //获取当前日期
        String datePath = new DateTime().toString("yyyy/MM/dd");
        filename = datePath + "/" + filename;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucketName, filename, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            String url = "https://" + bucketName + "." + endpoint + "/" + filename;

            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }
    //发布文章
    public Integer releaseArticle(ArticleRelease articleRelease) {
        int insert = articleReleaseMapper.insert(articleRelease);
        return insert;
    }


    public Integer deleteArticleById(long id) {
        //System.out.println("实现类id"+id);
        int i = articleReleaseMapper.deleteById(id);
        return i;
    }

    @Override
    public ArticleRelease findArticleById(Long id) {
        ArticleRelease articleRelease = articleReleaseMapper.selectById(id);
        return articleRelease;
    }

    @Override
    public Integer updateArticleById(ArticleRelease articleRelease) {
        int i = articleReleaseMapper.updateById(articleRelease);
        return i;
    }


}
